<template>
  <div style="margin-top: 40px">
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
      :disabled="readOnly"
    >
      <el-form-item v-show="false" label="id：" prop="id">
        <el-input v-model="ruleForm.id" />
      </el-form-item>
      <el-form-item label="菜品名称：" prop="name">
        <el-input v-model="ruleForm.name" placeholder="请输入菜品名称" />
      </el-form-item>
      <el-form-item label="菜品分类：" prop="foodTypeId">
        <el-select v-model="ruleForm.foodTypeId" placeholder="请选择">
          <el-option
            v-for="item in foodTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item id="price" label="菜品价格：" prop="price">
        <el-input v-model.number="ruleForm.price" placeholder="请输入菜品价格" />
      </el-form-item>
      <el-form-item id="priceUnit" label="价格单位：" prop="priceUnit">
        <el-input v-model="ruleForm.priceUnit" placeholder="请输入价格单位" />
      </el-form-item>
      <el-form-item label="是否招牌：" prop="isHot">
        <el-radio-group v-model="ruleForm.isHot">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否折扣：" prop="isDiscount">
        <el-radio-group v-model="ruleForm.isDiscount">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="菜品描述：" prop="remark">
        <el-input v-model="ruleForm.remark" type="textarea" :rows="4" placeholder="请输入菜品描述" />
      </el-form-item>
      <el-form-item label="菜品图片：" prop="img">
        <el-upload
          class="avatar-uploader"
          :action="this.action"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="foodImg" :src="foodImg" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
          <div slot="tip" class="el-upload__tip">只能上传jpeg、jpg、png、gif文件，且不超过2M</div>
        </el-upload>
      </el-form-item>
    </el-form>
    <div align="center" style="margin-top: 50px">
      <el-button @click="readOnly?handleEdit():handleSave()">{{ readOnly?'编辑':'保存' }}</el-button>
      <el-button @click="back">返回</el-button>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { getWbeRoot } from '../../api/web-site'
import sessionStorage from '../../assets/js/storage'

export default {
  name: 'DishesManageDetails',

  data () {
    return {
      foodId: '',
      readOnly: '',
      userId: '',

      ruleForm: {
        id: '',
        name: '',
        foodTypeId: '',
        img: '',
        price: '',
        priceUnit: '',
        remark: '',
        isHot: '',
        isDiscount: ''
      },

      rules: {
        name: [
          { required: true, message: '请输入菜品分类名称', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '价格不能为空', trigger: 'blur' },
          { type: 'number', message: '价格必须为数字值' }
        ],
        priceUnit: [
          { required: true, message: '价格单位不能为空', trigger: 'blur' }
        ]
      },

      foodTypeList: [{
        id: '',
        name: ''
      }],

      /* 菜品图片地址 */
      foodImg: '',
      /* 上传图片接口图片地址 */
      action: getWbeRoot() + '/api/upload/upload'
    }
  },

  created () {
    this.userId = sessionStorage.getItem('usrId')
    this.getFoodTypeList(this.userId)

    if (sessionStorage.getItem('type') === 'view') {
      this.foodId = sessionStorage.getItem('id')
      this.getFormData(this.foodId)
      this.readOnly = true
    } else if (sessionStorage.getItem('type') === 'edit') {
      this.foodId = sessionStorage.getItem('id')
      this.getFormData(this.foodId)
      this.readOnly = false
    } else if (sessionStorage.getItem('type') === 'add') {
      this.readOnly = false
    }
  },

  methods: {
    /**
     * 表单数据请求
     */
    getFormData (val) {
      axios.get(getWbeRoot() + '/api/food/findFoodById', {
        params: {
          foodId: val
        }
      }).then(
        response => {
          if (response.status === 200) {
            console.log(response.data)
            this.ruleForm = response.data
            this.getFoodImg(response.data.img)
          }
        }
      )
    },

    /**
     * 菜品类型列表请求
     */
    getFoodTypeList (val) {
      axios.get(getWbeRoot() + '/api/foodType/findFoodTypeByCurrentUser', {
        params: {
          userId: val
        }
      }).then(
        response => {
          if (response.status === 200) {
            this.foodTypeList = response.data
          }
        }
      )
    },

    /**
     * 编辑按钮
     */
    handleEdit () {
      this.readOnly = false
    },

    /**
     * 修改保存
     */
    handleSave () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          axios.post(getWbeRoot() + '/api/food/save', this.ruleForm
          ).then(
            response => {
              if (response.data.code === '200') {
                this.$message({
                  showClose: true,
                  message: response.data.msg,
                  type: 'success'
                })
                this.$router.push('variety-of-dishes-manage')
              } else {
                this.$message({
                  showClose: true,
                  message: response.data.msg,
                  type: 'error'
                })
              }
            }
          )
        } else {
          return false
        }
      })
    },

    /**
     * 返回
     */
    back () {
      this.$router.push('variety-of-dishes-manage')
    },

    /**
     * 图片上传
     * @param res
     * @param file
     */
    handleAvatarSuccess (res, file) {
      if (res.code === '200') {
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'success'
        })
        this.foodImg = URL.createObjectURL(file.raw)
        this.ruleForm.img = res.data
      } else {
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'error'
        })
      }
    },
    beforeAvatarUpload (file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/jpg' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('请上传jpeg、jpg、png、gif格式的图片')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    /**
     * @param fileName
     * 获取服务器文件路径
     */
    getFoodImg (fileName) {
      return fileName === '' ? this.foodImg = '' : this.foodImg = getWbeRoot() + '/upload/' + fileName
    }
  }
}
</script>

<style scoped>

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
#price{

}
#priceUnit{

}
</style>
